<template>
  <view class="slider-verify">
    <view class="slider-track">
      <view class="slider-btn" :style="{ left: sliderLeft + 'rpx' }" @touchstart="onTouchStart" @touchmove="onTouchMove" @touchend="onTouchEnd">
        <text>→</text>
      </view>
    </view>
    <view class="verify-tip">{{ verifyTip }}</view>
  </view>
</template>

<script>
export default {
  name: 'SliderVerify',
  data() {
    return {
      sliderLeft: 0,
      startX: 0,
      verifyTip: '请按住滑块，拖动到最右边',
      isVerified: false,
      trackWidth: 0
    };
  },
  props: {
    successCallback: {
      type: Function,
      default: () => {}
    },
    failCallback: {
      type: Function,
      default: () => {}
    }
  },
  mounted() {
    // 获取滑块轨道的宽度
    uni.createSelectorQuery().in(this).select('.slider-track').boundingClientRect((rect) => {
      if (rect) {
        this.trackWidth = rect.width;
      }
    }).exec();
  },
  methods: {
    onTouchStart(e) {
      if (this.isVerified) return;
      this.startX = e.touches[0].clientX;
    },
    onTouchMove(e) {
      if (this.isVerified) return;
      const currentX = e.touches[0].clientX;
      const moveX = currentX - this.startX;
      this.sliderLeft = Math.min(Math.max(0, this.sliderLeft + moveX), this.trackWidth - 50);
      this.startX = currentX;
    },
    onTouchEnd() {
      if (this.isVerified) return;
      if (this.sliderLeft >= this.trackWidth - 50) {
        this.verifyTip = '验证成功';
        this.isVerified = true;
        // 触发成功回调
        this.successCallback();
      } else {
        this.verifyTip = '验证失败，请重新滑动';
        this.sliderLeft = 0;
        // 触发失败回调
        this.failCallback();
      }
    }
  }
};
</script>

<style scoped>
.slider-verify {
  width: 100%;
  margin-top: 20px;
}

.slider-track {
  position: relative;
  width: 100%;
  height: 50px;
  background-color: #f0f0f0;
  border-radius: 25px;
  overflow: hidden;
}

.slider-btn {
  position: absolute;
  top: 0;
  left: 0;
  width: 50px;
  height: 50px;
  background-color: #007aff;
  border-radius: 25px;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #fff;
  font-size: 20px;
  cursor: pointer;
}

.verify-tip {
  margin-top: 10px;
  text-align: center;
  color: #666;
}
</style>